package com.vehiclesecure.config;

import com.vehiclesecure.model.User;
import com.vehiclesecure.model.Vehicle;
import com.vehiclesecure.service.UserService;
import com.vehiclesecure.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 车辆数据初始化器
 * 用于在开发环境中初始化示例车辆数据
 */
@Component
@Profile("dev")
public class VehicleDataInitializer implements CommandLineRunner {

    private final VehicleService vehicleService;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public VehicleDataInitializer(VehicleService vehicleService, UserService userService, 
                                   PasswordEncoder passwordEncoder) {
        this.vehicleService = vehicleService;
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void run(String... args) throws Exception {
        initializeSampleData();
    }

    private void initializeSampleData() {
        try {
            // 创建示例用户
            User adminUser = createUserIfNotExists("admin@vehiclesecure.com", "Admin", "User", "admin123", User.Role.ADMIN);
            User regularUser = createUserIfNotExists("user@vehiclesecure.com", "Regular", "User", "user123", User.Role.USER);
            User testUser = createUserIfNotExists("test@vehiclesecure.com", "Test", "User", "test123", User.Role.USER);

            // 创建示例车辆
            createSampleVehicles(adminUser, regularUser, testUser);

            System.out.println("车辆示例数据初始化完成！");
        } catch (Exception e) {
            System.err.println("初始化车辆数据时出错: " + e.getMessage());
        }
    }

    private User createUserIfNotExists(String email, String firstName, String lastName, String password, User.Role role) {
        return userService.findByEmail(email).orElseGet(() -> {
            User user = new User();
            user.setEmail(email);
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setPassword(passwordEncoder.encode(password));
            user.setRole(role);
            return userService.registerUser(user);
        });
    }

    private void createSampleVehicles(User adminUser, User regularUser, User testUser) {
        // 示例车辆1 - 丰田凯美瑞
        Vehicle vehicle1 = new Vehicle();
        vehicle1.setVin("1HGBH41JXMN109186");
        vehicle1.setLicensePlate("京A12345");
        vehicle1.setBrand("丰田");
        vehicle1.setModel("凯美瑞");
        vehicle1.setColor("黑色");
        vehicle1.setYear(2022);
        vehicle1.setFuelType("汽油");
        vehicle1.setTransmissionType("自动");
        vehicle1.setEngineCapacity(2.5);
        vehicle1.setVehicleType("轿车");
        vehicle1.setMileage(15000);
        vehicle1.setRegistrationDate(LocalDateTime.now().minusYears(1));
        vehicle1.setInsuranceExpiry(LocalDateTime.now().plusMonths(6));
        vehicle1.setLastMaintenance(LocalDateTime.now().minusMonths(2));
        vehicle1.setDeviceId("DEV001");
        vehicle1.setDeviceSerialNumber("SN123456789");
        vehicle1.setDeviceModel("VS-GPS-2022");
        vehicle1.setDeviceVersion("1.2.3");
        vehicle1.setStatus("ACTIVE");
        vehicle1.setIsActive(true);
        vehicle1.setIsStolen(false);
        vehicle1.setNotes("公司用车，定期保养");
        vehicle1.setTags(List.of("公司用车", "商务", "黑色"));
        vehicle1.setAuthorizedUsers(List.of(adminUser.getId(), regularUser.getId()));

        // 示例车辆2 - 宝马X5
        Vehicle vehicle2 = new Vehicle();
        vehicle2.setVin("5UX23EU00P9000001");
        vehicle2.setLicensePlate("沪B67890");
        vehicle2.setBrand("宝马");
        vehicle2.setModel("X5");
        vehicle2.setColor("白色");
        vehicle2.setYear(2023);
        vehicle2.setFuelType("汽油");
        vehicle2.setTransmissionType("自动");
        vehicle2.setEngineCapacity(3.0);
        vehicle2.setVehicleType("SUV");
        vehicle2.setMileage(8000);
        vehicle2.setRegistrationDate(LocalDateTime.now().minusMonths(8));
        vehicle2.setInsuranceExpiry(LocalDateTime.now().plusMonths(10));
        vehicle2.setLastMaintenance(LocalDateTime.now().minusMonths(1));
        vehicle2.setDeviceId("DEV002");
        vehicle2.setDeviceSerialNumber("SN987654321");
        vehicle2.setDeviceModel("VS-GPS-2023");
        vehicle2.setDeviceVersion("2.1.0");
        vehicle2.setStatus("ACTIVE");
        vehicle2.setIsActive(true);
        vehicle2.setIsStolen(false);
        vehicle2.setNotes("个人用车，配置齐全");
        vehicle2.setTags(List.of("个人用车", "豪华", "SUV"));
        vehicle2.setAuthorizedUsers(List.of(regularUser.getId()));

        // 示例车辆3 - 奥迪A6
        Vehicle vehicle3 = new Vehicle();
        vehicle3.setVin("WAUZZZ4F9EN000001");
        vehicle3.setLicensePlate("粤C24680");
        vehicle3.setBrand("奥迪");
        vehicle3.setModel("A6L");
        vehicle3.setColor("银色");
        vehicle3.setYear(2021);
        vehicle3.setFuelType("汽油");
        vehicle3.setTransmissionType("自动");
        vehicle3.setEngineCapacity(2.0);
        vehicle3.setVehicleType("轿车");
        vehicle3.setMileage(25000);
        vehicle3.setRegistrationDate(LocalDateTime.now().minusYears(2));
        vehicle3.setInsuranceExpiry(LocalDateTime.now().plusMonths(3));
        vehicle3.setLastMaintenance(LocalDateTime.now().minusMonths(3));
        vehicle3.setDeviceId("DEV003");
        vehicle3.setDeviceSerialNumber("SN555666777");
        vehicle3.setDeviceModel("VS-GPS-2021");
        vehicle3.setDeviceVersion("1.8.5");
        vehicle3.setStatus("ACTIVE");
        vehicle3.setIsActive(true);
        vehicle3.setIsStolen(false);
        vehicle3.setNotes("家庭用车，保养良好");
        vehicle3.setTags(List.of("家庭用车", "商务", "轿车"));
        vehicle3.setAuthorizedUsers(List.of(testUser.getId()));

        // 示例车辆4 - 特斯拉Model 3
        Vehicle vehicle4 = new Vehicle();
        vehicle4.setVin("5YJ3E1EA8PF000001");
        vehicle4.setLicensePlate("京D13579");
        vehicle4.setBrand("特斯拉");
        vehicle4.setModel("Model 3");
        vehicle4.setColor("红色");
        vehicle4.setYear(2023);
        vehicle4.setFuelType("电动");
        vehicle4.setTransmissionType("自动");
        vehicle4.setEngineCapacity(0.0); // 电动车无排量
        vehicle4.setVehicleType("轿车");
        vehicle4.setMileage(5000);
        vehicle4.setRegistrationDate(LocalDateTime.now().minusMonths(6));
        vehicle4.setInsuranceExpiry(LocalDateTime.now().plusMonths(12));
        vehicle4.setLastMaintenance(LocalDateTime.now().minusMonths(1));
        vehicle4.setDeviceId("DEV004");
        vehicle4.setDeviceSerialNumber("SN888999000");
        vehicle4.setDeviceModel("VS-GPS-2023E");
        vehicle4.setDeviceVersion("3.0.1");
        vehicle4.setStatus("ACTIVE");
        vehicle4.setIsActive(true);
        vehicle4.setIsStolen(false);
        vehicle4.setNotes("新能源汽车，零排放");
        vehicle4.setTags(List.of("新能源汽车", "电动", "红色"));
        vehicle4.setAuthorizedUsers(List.of(adminUser.getId(), testUser.getId()));

        // 创建车辆
        try {
            vehicleService.createVehicle(vehicle1);
            vehicleService.createVehicle(vehicle2);
            vehicleService.createVehicle(vehicle3);
            vehicleService.createVehicle(vehicle4);

            // 绑定车辆到用户
            vehicleService.bindVehicleToUser(vehicle1.getId(), adminUser.getId());
            vehicleService.bindVehicleToUser(vehicle2.getId(), regularUser.getId());
            vehicleService.bindVehicleToUser(vehicle3.getId(), testUser.getId());
            vehicleService.bindVehicleToUser(vehicle4.getId(), adminUser.getId());

        } catch (Exception e) {
            System.err.println("创建示例车辆时出错: " + e.getMessage());
        }
    }
}